package com.lonely.goods.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lonely.common.core.domain.BaseEntity;
import com.lonely.common.enums.CommonStatus;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.goods.domain.dto.goods.GoodsFileDTO;
import com.lonely.goods.domain.dto.goods.GoodsDesignInfoSubmitDTO;
import com.lonely.goods.domain.entity.SysGoodsFile;
import com.lonely.goods.enums.GoodsEnum;
import com.lonely.goods.mapper.SysGoodsFileMapper;
import com.lonely.goods.service.IGoodsFileService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 黄志标
 * @date: 2025/6/25 15:42
 * @description: 商品文件接口实现
 */
@Service
public class GoodsFileServiceImpl extends ServiceImpl<SysGoodsFileMapper, SysGoodsFile> implements IGoodsFileService {

    /**
     * 编辑商品款信息对应的文件信息
     *
     * @param submitDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitGoodsDesignInfoFiles(GoodsDesignInfoSubmitDTO submitDTO) {
        // 比较文件列表是否有修改
        List<SysGoodsFile> existsGoodsFiles = super.list(new LambdaQueryWrapper<SysGoodsFile>()
                .eq(SysGoodsFile::getGoodsId, submitDTO.getId())
                .in(SysGoodsFile::getType, Lists.newArrayList(GoodsEnum.GoodsFileTypeEnum.PATTERN_MAKING_BEFORE.getType(),
                        GoodsEnum.GoodsFileTypeEnum.PATTERN_MAKING_AFTER.getType(),
                        GoodsEnum.GoodsFileTypeEnum.PAPER_PATTERN.getType())));
        List<String> existsFileKeys = existsGoodsFiles.stream().map(x -> String.format("%s-%s", x.getName(), x.getUrl())).collect(Collectors.toList());

        List<GoodsFileDTO> submitFiles = CollUtil.unionAll(submitDTO.getPatternMakingBeforeFiles(), submitDTO.getPatternMakingAfterFiles(), submitDTO.getPaperPatternFiles());
        List<String> submitFileKeys = submitFiles.stream().map(x -> String.format("%s-%s", x.getName(), x.getUrl())).collect(Collectors.toList());

        // 找到待删除的文件
        List<Long> needRemoveFiles = existsGoodsFiles.stream().filter(x -> !submitFileKeys.contains(String.format("%s-%s", x.getName(), x.getUrl()))).collect(Collectors.toList())
                .stream().map(BaseEntity::getId).collect(Collectors.toList());


        // 删除待删除的文件
        if (CollUtil.isNotEmpty(needRemoveFiles)) {
            super.removeByIds(needRemoveFiles);
        }

        // 处理待新增的文件集合
        List<GoodsFileDTO> needAddFiles = submitFiles.stream().filter(x -> !existsFileKeys.contains(String.format("%s-%s", x.getName(), x.getUrl()))).collect(Collectors.toList());
        List<String> needAddFileIds = needAddFiles.stream().map(GoodsFileDTO::getId).distinct().collect(Collectors.toList());
        List<SysGoodsFile> goodsFiles = new ArrayList<>();
        if (CollUtil.isNotEmpty(submitDTO.getPatternMakingBeforeFiles())) {
            goodsFiles.addAll(submitDTO.getPatternMakingBeforeFiles().stream()
                    .filter(x -> needAddFileIds.contains(x.getId()))
                    .map(x -> {
                        SysGoodsFile sysGoodsFile = buildBaseGoodsInfo(submitDTO.getId(), x);
                        sysGoodsFile.setType(GoodsEnum.GoodsFileTypeEnum.PATTERN_MAKING_BEFORE.getType());
                        return sysGoodsFile;
                    }).collect(Collectors.toList()));
        }


        if (CollUtil.isNotEmpty(submitDTO.getPatternMakingAfterFiles())) {
            goodsFiles.addAll(submitDTO.getPatternMakingAfterFiles().stream()
                    .filter(x -> needAddFileIds.contains(x.getId()))
                    .map(x -> {
                        SysGoodsFile sysGoodsFile = buildBaseGoodsInfo(submitDTO.getId(), x);
                        sysGoodsFile.setType(GoodsEnum.GoodsFileTypeEnum.PATTERN_MAKING_AFTER.getType());
                        return sysGoodsFile;
                    }).collect(Collectors.toList()));
        }


        if (CollUtil.isNotEmpty(submitDTO.getPaperPatternFiles())) {
            goodsFiles.addAll(submitDTO.getPaperPatternFiles().stream()
                    .filter(x -> needAddFileIds.contains(x.getId()))
                    .map(x -> {
                        SysGoodsFile sysGoodsFile = buildBaseGoodsInfo(submitDTO.getId(), x);
                        sysGoodsFile.setType(GoodsEnum.GoodsFileTypeEnum.PAPER_PATTERN.getType());
                        return sysGoodsFile;
                    }).collect(Collectors.toList()));
        }

        if (CollUtil.isNotEmpty(goodsFiles)) {
            super.saveBatch(goodsFiles);
        }
    }


    /**
     * 构建基础的商品文件信息
     *
     * @param goodsId
     * @param goodsFileDTO
     * @return
     */
    private SysGoodsFile buildBaseGoodsInfo(Long goodsId, GoodsFileDTO goodsFileDTO) {
        SysGoodsFile sysGoodsFile = new SysGoodsFile();
        sysGoodsFile.setGoodsId(goodsId);
        sysGoodsFile.setName(goodsFileDTO.getName());
        sysGoodsFile.setUrl(goodsFileDTO.getUrl());
        sysGoodsFile.setStatus(CommonStatus.ENABLE.code);
        sysGoodsFile.setCreateBy(SecurityUtils.getUserId());
        sysGoodsFile.setUpdateBy(SecurityUtils.getUserId());
        return sysGoodsFile;
    }
}
